package filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;



@WebFilter
(
	description = "字符编码过滤器",
	filterName = "EncodingFilter",
	urlPatterns = {"/*"},
	asyncSupported = true
)


public class EncodingFilter implements Filter
{

	public void init(FilterConfig filterConfig)
			throws ServletException
	{
		
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException
	{
		HttpServletRequest http_request = (HttpServletRequest)request;

		if (http_request.getMethod().equals("GET"))
		{
			http_request = new EncodingRequestWrapper(http_request);
		}
		else
			request.setCharacterEncoding("UTF-8");
		
		response.setCharacterEncoding("UTF-8");
		chain.doFilter(http_request, response);
	}

}



class EncodingRequestWrapper extends HttpServletRequestWrapper
{

	public EncodingRequestWrapper(HttpServletRequest request)
	{
		super(request);
	}
	
	@Override
    public String getParameter(String name) {
        String value = this.getRequest().getParameter(name);
        
        if (value != null && !value.equals(""))
        {
        	try
        	{
				value = new String(value.getBytes(), "UTF-8");
			}
        	catch (UnsupportedEncodingException e) {e.printStackTrace();}
        }
        
        return value;
    }
}









